package com.redwine.app;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.adapter.MerchantsHomePageAdapter;
import com.redwine.app.chat.ChatActivity;
import com.redwine.app.chat.ChatConstant;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.MerchantsPageResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.AlertDialog;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 商家主页
 * 作者：gassion on 17/8/23 23:02
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MerchantsHomePageActivity extends BaseActivity {

    @ViewInject(R.id.merchants_home_page_iv_pic)
    ImageView merchantsHomePageIvPic;
    @ViewInject(R.id.merchants_home_page_iv_user_flag)
    ImageView merchantsHomePageIvUserFlag;
    @ViewInject(R.id.merchants_home_page_tv_name)
    TextView merchantsHomePageTvName;
    @ViewInject(R.id.merchants_home_page_tv_address)
    TextView merchantsHomePageTvAddress;
    @ViewInject(R.id.merchants_home_page_refresh_list_view)
    PullToRefreshListView mListView;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    @ViewInject(R.id.merchants_home_page_tv_send_message)
    private TextView mSendMessage;
    @ViewInject(R.id.merchants_home_page_tv_phone_call)
    private TextView mPhoneCall;
    @ViewInject(R.id.merchants_home_page_layout_all)
    LinearLayout mLayoutAll;
    private int page = 1;//默认加载第一页
    private View view;
    public static final String PUBLISH_UID = "PUBLISH_UID";
    public String publish_uid;
    public boolean isAddContact = false;
    private MerchantsHomePageAdapter merchantsHomePageAdapter;
    private MerchantsPageResponse.DataEntityX.SupplierInfoEntity supplier_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(this).inflate(R.layout.activity_merchants_home_page, null);
        setContentView(view);
        ViewUtils.inject(this, view);
        initView();
        requestListData();
    }

    private void initView() {
        Intent intent = getIntent();
        if (null != intent) {
            publish_uid = intent.getStringExtra(PUBLISH_UID);
        }
        headerTitle.setText(R.string.merchant_home_page);
        layoutBack.setVisibility(View.VISIBLE);
        if (Global.user.getUid().equals(publish_uid)) {
            mSendMessage.setTextColor(getResources().getColor(R.color.color_7f7f7f));
            mSendMessage.setBackgroundResource(R.drawable.gray_shape);
            mPhoneCall.setBackgroundResource(R.drawable.gray_shape);
            mPhoneCall.setTextColor(getResources().getColor(R.color.color_7f7f7f));
            mSendMessage.setEnabled(false);
            mPhoneCall.setEnabled(false);
        } else {
            mSendMessage.setBackgroundResource(R.drawable.common_shape_select);
            mSendMessage.setTextColor(getResources().getColor(R.color.white));
            mPhoneCall.setBackgroundResource(R.drawable.common_shape_select);
            mPhoneCall.setTextColor(getResources().getColor(R.color.white));
            mSendMessage.setEnabled(true);
            mPhoneCall.setEnabled(true);
        }
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                requestListData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page += 1;
                requestListData();
            }
        });
        mListView.setOnActionMoveListener(new PullToRefreshBase.OnActionMove() {
            @Override
            public void onMove(boolean isMove) {
                setUpdateTime(mListView);
            }
        });
        merchantsHomePageAdapter = new MerchantsHomePageAdapter(this);
        mListView.setAdapter(merchantsHomePageAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int newPosition = position - mListView.getRefreshableView().getHeaderViewsCount();
            }
        });

    }

    /**
     * 请求列表数据
     */
    private void requestListData() {
        String url = NetworkConstants.BUSINESS_PAGE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("size", "20");
        params.put("page", String.valueOf(page));
        params.put("uid", Global.user.getUid());
        params.put("publish_uid", publish_uid);
        GsonRequest<MerchantsPageResponse> request = new GsonRequest<>(url, Request.Method.POST,
                MerchantsPageResponse.class, false, params, new Response.Listener<MerchantsPageResponse>() {
            @Override
            public void onResponse(MerchantsPageResponse response) {
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                if (response.isSuccess()) {
                    mLayoutAll.setVisibility(View.VISIBLE);
                    MerchantsPageResponse.DataEntityX responseData = response.getData();
                    updateView(responseData);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    private void updateView(MerchantsPageResponse.DataEntityX responseData) {
        supplier_info = responseData.getSupplier_info();
        isAddContact = supplier_info.isFriend_status();
        if (!isAddContact) {
            merchantsHomePageIvUserFlag.setBackgroundResource(R.mipmap.icon_del_friends);
        } else {
            merchantsHomePageIvUserFlag.setBackgroundResource(R.mipmap.icon_add_friends);
        }
        BitmapUtils.loadImage(merchantsHomePageIvPic, supplier_info.getAvatar(), BitmapUtils.THE_ARTICLE);
        merchantsHomePageTvName.setText(supplier_info.getName());
        if (supplier_info.getSex()) {
            merchantsHomePageTvName.setCompoundDrawables(null, null, getIdDrawable(R.mipmap.icon_male), null);
        } else {
            merchantsHomePageTvName.setCompoundDrawables(null, null, getIdDrawable(R.mipmap.icon_female), null);
        }
        merchantsHomePageTvAddress.setText(supplier_info.getTitle());

        MerchantsPageResponse.DataEntityX.RedwineInfoEntity redwine_info = responseData.getRedwine_info();
        List<MerchantsPageResponse.DataEntityX.RedwineInfoEntity.DataEntity> redwine_infoData = redwine_info.getData();
        merchantsHomePageAdapter.setData(page, redwine_infoData);
        if (redwine_info.getPage() != redwine_info.getAllpage()) {
            mListView.setMode(PullToRefreshBase.Mode.BOTH);
        } else {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
    }

    @OnClick({R.id.layout_back, R.id.merchants_home_page_tv_phone_call, R.id.merchants_home_page_tv_send_message, R.id.merchants_home_page_iv_user_flag})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.merchants_home_page_tv_phone_call:
                final String mobile = supplier_info.getMobile();
                if (!TextUtils.isEmpty(mobile)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantsHomePageActivity.this);
                    builder.setMessage(getString(R.string.make_a_phone_call_hint) + mobile);
                    builder.setNegativeButton(getString(R.string.cancel_phone_call), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton(getString(R.string.confirm_phone_call), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mobile));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    });
                    AlertDialog mDialog = builder.create();
                    mDialog.setCancelable(false);
                    mDialog.show();
                }
                break;

            case R.id.merchants_home_page_tv_send_message:
                Intent intent = new Intent(MerchantsHomePageActivity.this, ChatActivity.class);
                intent.putExtra(ChatConstant.EXTRA_USER_ID, supplier_info.getUid());//传递用户的唯一id
                intent.putExtra(ChatConstant.EXTRA_USER_NICK_NAME, supplier_info.getName());//传递用户的唯一id
                intent.putExtra(ChatConstant.EXTRA_USER_AVATAR, supplier_info.getAvatar());
                startActivity(intent);
                break;

            case R.id.merchants_home_page_iv_user_flag:
                if (!isAddContact) {
                    requestAddData(supplier_info.getUid());
                } else {
                    requestDelContact(supplier_info.getUid());
                }
                break;

        }
    }


    /**
     * 添加联系人
     */
    protected void requestAddData(String private_id) {
        String url = NetworkConstants.FRIEND_ADD_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("friend_uid", private_id);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    Toast.makeText(MerchantsHomePageActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    isAddContact = true;
                    merchantsHomePageIvUserFlag.setBackgroundResource(R.mipmap.icon_add_friends);
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MESSAGE_DATA));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    private void requestDelContact(String friend_uid) {
        String url = NetworkConstants.FRIEND_DEL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("friend_uid", friend_uid);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    isAddContact = false;
                    Toast.makeText(MerchantsHomePageActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MESSAGE_DATA));
                    merchantsHomePageIvUserFlag.setBackgroundResource(R.mipmap.icon_del_friends);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

}
